package com.wbdgj.ui.coupon;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.google.gson.internal.LinkedTreeMap;
import com.google.zxing.WriterException;
import com.igexin.sdk.PushManager;
import com.wbdgj.R;
import com.wbdgj.base.BaseActivity;
import com.wbdgj.base.BaseApplication;
import com.wbdgj.http.HttpAdapter;
import com.wbdgj.http.OnNoResponseListener;
import com.wbdgj.http.OnResponseListener;
import com.wbdgj.model.ResultObjectModel;
import com.wbdgj.model.ResultUrlModel;
import com.wbdgj.ui.booking.BookingActivity;
import com.wbdgj.ui.branch.BranchDetailActivity;
import com.wbdgj.ui.login.LoginActivity;
import com.wbdgj.ui.store.StoreCofeActivity;
import com.wbdgj.ui.store.StoreHotelActivity;
import com.wbdgj.ui.store.cafe.StoreCofeFragment01;
import com.wbdgj.ui.uitool.ShareBoard;
import com.wbdgj.ui.uitool.ShareBoardlistener;
import com.wbdgj.ui.uitool.SnsPlatform;
import com.wbdgj.ui.word_compaign.CouponWordCompaignDialogActivity;
import com.wbdgj.ui.word_compaign.WordCompaignDialogActivity;
import com.wbdgj.utils.QRCodeUtil;
import com.wbdgj.utils.SpKeyUtils;
import com.wbdgj.utils.ToastUtils;
import com.wbdgj.views.RichTextView;

import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import cn.jiguang.share.android.api.JShareInterface;
import cn.jiguang.share.android.api.PlatActionListener;
import cn.jiguang.share.android.api.Platform;
import cn.jiguang.share.android.api.ShareParams;
import cn.jiguang.share.facebook.Facebook;
import cn.jiguang.share.facebook.messenger.FbMessenger;
import cn.jiguang.share.qqmodel.QQ;
import cn.jiguang.share.qqmodel.QZone;
import cn.jiguang.share.twitter.Twitter;
import cn.jiguang.share.wechat.Wechat;
import cn.jiguang.share.wechat.WechatFavorite;
import cn.jiguang.share.wechat.WechatMoments;
import cn.jiguang.share.weibo.SinaWeibo;
import cn.jiguang.share.weibo.SinaWeiboMessage;
import in.srain.cube.views.ptr.PtrClassicFrameLayout;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;
import retrofit2.Call;

public class CouponDetailAbleActivity extends BaseActivity implements PtrHandler {

    private Context context = this;

    @BindView(R.id.pfl_root)
    PtrClassicFrameLayout pfl_root;

    @BindView(R.id.text_top_left)
    TextView text_top_left;

    @BindView(R.id.NAME)
    TextView NAME;
    @BindView(R.id.AMOUNT)
    TextView AMOUNT;
    @BindView(R.id.MIN_AMOUNT)
    TextView MIN_AMOUNT;
    @BindView(R.id.M_KEY)
    TextView M_KEY;
    @BindView(R.id.USE_BEG)
    TextView USE_BEG;
    @BindView(R.id.BRANCH_NAME)
    TextView BRANCH_NAME;
    @BindView(R.id.DESCRIBES)
    RichTextView DESCRIBES;

    @BindView(R.id.ewmImg)
    ImageView ewmImg;
    @BindView(R.id.txmImg)
    ImageView txmImg;

    private List<LinkedTreeMap> linkedTreeMapsCd ;

    private String id;
    private String BRANCH_ID;
    private static final int REQUEST_PERMISSION = 0;

    private String urlStr;
    private int mAction = Platform.ACTION_SHARE;
    private ShareBoard mShareBoard;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            String toastMsg = (String) msg.obj;
            Toast.makeText(context, toastMsg, Toast.LENGTH_SHORT).show();
        }
    };

    private DecimalFormat decimalFormat;
    private String BRANCH_ATTRIBUTE;
    private String branchName;

    @Override
    protected int getLayoutResId() {
        return R.layout.ui_coupon_detail_able;
    }

    @Override
    protected void initView() {
        decimalFormat = new DecimalFormat("###################.###########");
        id = getIntent().getStringExtra("id");
        pfl_root.setEnabledNextPtrAtOnce(true);
        pfl_root.setLastUpdateTimeRelateObject(this);
        pfl_root.setPtrHandler(this);
        pfl_root.setKeepHeaderWhenRefresh(true);

        PackageManager pkgManager = getPackageManager();
        // 读写 sd card 权限非常重要, android6.0默认禁止的, 建议初始化之前就弹窗让用户赋予该权限
        boolean sdCardWritePermission =
                pkgManager.checkPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, getPackageName()) == PackageManager.PERMISSION_GRANTED;

        if (Build.VERSION.SDK_INT >= 23 && !sdCardWritePermission ) {
            requestPermission();
        }

        v2info();
        permit();
        validate();

        try {
            // 根据字符串生成二维码图片并显示在界面上，第二个参数为图片的大小（310*310）
            Bitmap bitmapQRCode = QRCodeUtil.createQRCode(id+"",
                    710);
            ewmImg.setImageBitmap(bitmapQRCode);
        } catch (WriterException e) {
            e.printStackTrace();
        }

        txmImg.setImageBitmap(QRCodeUtil.creatBarcode(
                getApplicationContext(), id+"", 100, 30, false));

        findViewById(R.id.text_top_right).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (ContextCompat.checkSelfPermission(context,
                        android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(CouponDetailAbleActivity.this
                            , new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, 10);
                    ToastUtils.toastShort("请打开您设备上的照片,媒体内容和文件访问权限!");
                    return;
                }
                appCouponcreateUrl();
            }
        });

        findViewById(R.id.qwmdBtn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                BaseApplication.getInstance().getSpUtil().putString(SpKeyUtils.HOTEL_ID, BRANCH_ID);
                BaseApplication.getInstance().getSpUtil().putString(SpKeyUtils.HOTEL_NAME, branchName);
                if(!TextUtils.isEmpty(BRANCH_ATTRIBUTE)){
                    if(BRANCH_ATTRIBUTE.equals("0")){
                        startActivity(new Intent(context, StoreCofeActivity.class));
                    }else if(BRANCH_ATTRIBUTE.equals("1")){
                        startActivity(new Intent(context, BookingActivity.class));
                    }else{
                        startActivity(new Intent(context, StoreHotelActivity.class));
                    }
                }else{
                    startActivity(new Intent(context, StoreCofeActivity.class));
                }
            }
        });
        findViewById(R.id.ljhcLay).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                BaseApplication.getInstance().setlinkedTreeMapList(linkedTreeMapsCd);
                startActivityForResult(new Intent(context, CouponWordCompaignDialogActivity.class), 1);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if ( resultCode == 1 ){
            finish();
        }
    }

    @Override
    public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
        return PtrDefaultHandler.checkContentCanBePulledDown(frame, content, header);
    }

    @Override
    public void onRefreshBegin(PtrFrameLayout frame) {
        v2info();
        permit();
        validate();
        pfl_root.refreshComplete();
    }

    private void v2info() {
        Call<ResultObjectModel> call = HttpAdapter.getSerives().v2info(id, BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.TOKEN));
        call.enqueue(new OnResponseListener<ResultObjectModel>(context) {
            @Override
            protected void onSuccess(ResultObjectModel userModelBaseResultModel) {
                if(userModelBaseResultModel.getResultCode().equals("0000")){
                    LinkedTreeMap linkedTreeMap = (LinkedTreeMap) userModelBaseResultModel.getData();
                    text_top_left.setText(linkedTreeMap.get("TYPE_NAME")+"");
                    NAME.setText(linkedTreeMap.get("NAME")+"");
                    M_KEY.setText(id);

                    if(linkedTreeMap.containsKey("AMOUNT")){
                        AMOUNT.setText(decimalFormat.format(linkedTreeMap.get("AMOUNT"))+"");
                        if (decimalFormat.format(linkedTreeMap.get("AMOUNT")).equals("0")){
                            MIN_AMOUNT.setVisibility(View.GONE);
                            findViewById(R.id.swqLay).setVisibility(View.GONE);
                        }else{
                            MIN_AMOUNT.setVisibility(View.VISIBLE);
                            findViewById(R.id.swqLay).setVisibility(View.VISIBLE);
                            MIN_AMOUNT.setText("消费满"+ decimalFormat.format(linkedTreeMap.get("MIN_AMOUNT"))+"元使用");
                        }
                    }

                    if (linkedTreeMap.containsKey("DESCRIBES")){
                        DESCRIBES.setRichText(linkedTreeMap.get("DESCRIBES")+"");
                    }

                    if (linkedTreeMap.containsKey("ABLE_BRANCH_NAME")){
                        BRANCH_NAME.setText(linkedTreeMap.get("ABLE_BRANCH_NAME")+"");
                        BRANCH_NAME.setText(linkedTreeMap.get("ABLE_BRANCH_NAME")+"");
                    }else{
                        BRANCH_NAME.setText(linkedTreeMap.get("BRANCH_NAME")+"");
                    }

                    USE_BEG.setText("有效期："+formatDate1(linkedTreeMap.get("USE_BEG")+"")+" 至 "+ formatDate1(linkedTreeMap.get("USE_END")+""));

                    BRANCH_ID = decimalFormat.format(linkedTreeMap.get("BRANCH_ID"));
                    queryBranch();
                }else if (userModelBaseResultModel.getResultCode().equals("1111")){
                    ToastUtils.toastShort("账号没有登录或在其它地方登录");
                    BaseApplication.getInstance().getSpUtil().putString(SpKeyUtils.TOKEN, "");
                    BaseApplication.getInstance().getSpUtil().putString(SpKeyUtils.IS_AUTO_LOGIN, "2");
                    PushManager.getInstance().unBindAlias(context, BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.LOGIN_PHONE), false, BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.CID));
                    Intent intent = new Intent(context, LoginActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                }else{
                    ToastUtils.toastShort(userModelBaseResultModel.getResultMsg());
                }
            }
        });
    }

    private void permit() {
        Call<ResultObjectModel> call = HttpAdapter.getSerives().permit(id, BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.TOKEN));
        call.enqueue(new OnResponseListener<ResultObjectModel>(context) {
            @Override
            protected void onSuccess(ResultObjectModel userModelBaseResultModel) {
                if(userModelBaseResultModel.getResultCode().equals("0000")){
                    findViewById(R.id.text_top_right).setVisibility(View.VISIBLE);
                }else if (userModelBaseResultModel.getResultCode().equals("1111")){
                    ToastUtils.toastShort("账号没有登录或在其它地方登录");
                    BaseApplication.getInstance().getSpUtil().putString(SpKeyUtils.TOKEN, "");
                    BaseApplication.getInstance().getSpUtil().putString(SpKeyUtils.IS_AUTO_LOGIN, "2");
                    PushManager.getInstance().unBindAlias(context, BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.LOGIN_PHONE), false, BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.CID));
                    Intent intent = new Intent(context, LoginActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                }else{
                    findViewById(R.id.text_top_right).setVisibility(View.GONE);
                }
            }
        });
    }

    private void validate() {
        Call<ResultObjectModel> call = HttpAdapter.getSerives().validate(id, BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.TOKEN));
        call.enqueue(new OnResponseListener<ResultObjectModel>(context) {
            @Override
            protected void onSuccess(ResultObjectModel userModelBaseResultModel) {
                if(userModelBaseResultModel.getResultCode().equals("0000")){
                    findViewById(R.id.ljhcLay).setVisibility(View.VISIBLE);
                    linkedTreeMapsCd = new ArrayList<>();
                    LinkedTreeMap linkedTreeMap = (LinkedTreeMap) userModelBaseResultModel.getData();
                    linkedTreeMapsCd = (List<LinkedTreeMap>) linkedTreeMap.get("data");
                }else if (userModelBaseResultModel.getResultCode().equals("1111")){
                    ToastUtils.toastShort("账号没有登录或在其它地方登录");
                    BaseApplication.getInstance().getSpUtil().putString(SpKeyUtils.TOKEN, "");
                    BaseApplication.getInstance().getSpUtil().putString(SpKeyUtils.IS_AUTO_LOGIN, "2");
                    PushManager.getInstance().unBindAlias(context, BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.LOGIN_PHONE), false, BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.CID));
                    Intent intent = new Intent(context, LoginActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                }else{
                    findViewById(R.id.ljhcLay).setVisibility(View.GONE);
                }
            }
        });
    }

    private void queryBranch() {
        Call<ResultObjectModel> call = HttpAdapter.getSerives().queryBranch(BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.TOKEN), BRANCH_ID);
        call.enqueue(new OnNoResponseListener<ResultObjectModel>(context) {
            @Override
            protected void onSuccess(ResultObjectModel userModelBaseResultModel) {
                if(userModelBaseResultModel.getResultCode().equals("0000")){
                    DecimalFormat decimalFormat = new DecimalFormat("###################.###########");
                    LinkedTreeMap linkedTreeMap = (LinkedTreeMap) userModelBaseResultModel.getData();
                    if(linkedTreeMap.containsKey("BRANCH_ATTRIBUTE")){
                        BRANCH_ATTRIBUTE = decimalFormat.format(linkedTreeMap.get("BRANCH_ATTRIBUTE"));
                    }
                    branchName = linkedTreeMap.get("NAME")+"";
                }else if (userModelBaseResultModel.getResultCode().equals("1111")){
                    ToastUtils.toastShort("账号没有登录或在其它地方登录");
                    BaseApplication.getInstance().getSpUtil().putString(SpKeyUtils.TOKEN, "");
                    BaseApplication.getInstance().getSpUtil().putString(SpKeyUtils.IS_AUTO_LOGIN, "2");
                    PushManager.getInstance().unBindAlias(context, BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.LOGIN_PHONE), false, BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.CID));
                    Intent intent = new Intent(context, LoginActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                }
            }
        });
    }

    private void appCouponcreateUrl() {
        Call<ResultUrlModel> call = HttpAdapter.getSerives().appCouponcreateUrl(BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.TOKEN), id);
        call.enqueue(new OnResponseListener<ResultUrlModel>(context) {
            @Override
            protected void onSuccess(ResultUrlModel userModelBaseResultModel) {
                if(userModelBaseResultModel.getResultCode().equals("0000")){
                    urlStr = HttpAdapter.HEAD_URL + userModelBaseResultModel.getUrl();
                    mAction = Platform.ACTION_SHARE;
                    showBroadView();
                }else if (userModelBaseResultModel.getResultCode().equals("1111")){
                    ToastUtils.toastShort("账号没有登录或在其它地方登录");
                    BaseApplication.getInstance().getSpUtil().putString(SpKeyUtils.TOKEN, "");
                    BaseApplication.getInstance().getSpUtil().putString(SpKeyUtils.IS_AUTO_LOGIN, "2");
                    PushManager.getInstance().unBindAlias(context, BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.LOGIN_PHONE), false, BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.CID));
                    Intent intent = new Intent(context, LoginActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                }else{
                    ToastUtils.toastShort(userModelBaseResultModel.getResultMsg());
                }
            }
        });
    }

    private void showBroadView() {
        if (mShareBoard == null) {
            mShareBoard = new ShareBoard(this);
            List<String> platforms = JShareInterface.getPlatformList();
            if (platforms != null) {
                Iterator var2 = platforms.iterator();
                while (var2.hasNext()) {
                    String temp = (String) var2.next();
                    SnsPlatform snsPlatform = createSnsPlatform(temp);
                    mShareBoard.addPlatform(snsPlatform);
                }
            }
            mShareBoard.setShareboardclickCallback(mShareBoardlistener);
        }
        mShareBoard.show();
    }

    private ShareBoardlistener mShareBoardlistener = new ShareBoardlistener() {
        @Override
        public void onclick(SnsPlatform snsPlatform, String platform) {

            switch (mAction) {
                case Platform.ACTION_SHARE:
//                    progressDialog.show();
                    //这里以分享链接为例
                    ShareParams shareParams = new ShareParams();
                    shareParams.setShareType(Platform.SHARE_WEBPAGE);
                    shareParams.setTitle("我正在使用全城VIP转赠优惠券，快来领取吧！");
                    shareParams.setText("领取优惠券");
                    shareParams.setShareType(Platform.SHARE_WEBPAGE);
                    shareParams.setUrl(urlStr);
//                    shareParams.setUrl("http://www.ahxfk.com/");
                    shareParams.setImagePath(BaseApplication.ImagePath);
                    JShareInterface.share(platform, shareParams, mShareListener);
                    break;
                default:
                    break;
            }
        }
    };

    private PlatActionListener mShareListener = new PlatActionListener() {
        @Override
        public void onComplete(Platform platform, int action, HashMap<String, Object> data) {
            if (handler != null) {
                Message message = handler.obtainMessage();
                message.obj = "分享成功";
                handler.sendMessage(message);
            }
        }

        @Override
        public void onError(Platform platform, int action, int errorCode, Throwable error) {
            Log.e("zp", "error:" + errorCode + ",msg:" + error);
            if (handler != null) {
                Message message = handler.obtainMessage();
                message.obj = "分享失败:" + error.getMessage() + "---" + errorCode;
                handler.sendMessage(message);
            }
        }

        @Override
        public void onCancel(Platform platform, int action) {
            if (handler != null) {
                Message message = handler.obtainMessage();
                message.obj = "分享取消";
                handler.sendMessage(message);
            }
        }
    };

    public static SnsPlatform createSnsPlatform(String platformName) {
        String mShowWord = platformName;
        String mIcon = "";
        String mGrayIcon = "";
        String mKeyword = platformName;
        if (Wechat.Name.equals(platformName)) {
            mIcon = "jiguang_socialize_wechat";
            mGrayIcon = "jiguang_socialize_wechat";
            mShowWord = "jiguang_socialize_text_weixin_key";
        } else if (WechatMoments.Name.equals(platformName)) {
            mIcon = "jiguang_socialize_wxcircle";
            mGrayIcon = "jiguang_socialize_wxcircle";
            mShowWord = "jiguang_socialize_text_weixin_circle_key";

        } else if (WechatFavorite.Name.equals(platformName)) {
            mIcon = "jiguang_socialize_wxfavorite";
            mGrayIcon = "jiguang_socialize_wxfavorite";
            mShowWord = "jiguang_socialize_text_weixin_favorite_key";

        } else if (SinaWeibo.Name.equals(platformName)) {
            mIcon = "jiguang_socialize_sina";
            mGrayIcon = "jiguang_socialize_sina";
            mShowWord = "jiguang_socialize_text_sina_key";
        } else if (SinaWeiboMessage.Name.equals(platformName)) {
            mIcon = "jiguang_socialize_sina";
            mGrayIcon = "jiguang_socialize_sina";
            mShowWord = "jiguang_socialize_text_sina_msg_key";
        } else if (QQ.Name.equals(platformName)) {
            mIcon = "jiguang_socialize_qq";
            mGrayIcon = "jiguang_socialize_qq";
            mShowWord = "jiguang_socialize_text_qq_key";

        } else if (QZone.Name.equals(platformName)) {
            mIcon = "jiguang_socialize_qzone";
            mGrayIcon = "jiguang_socialize_qzone";
            mShowWord = "jiguang_socialize_text_qq_zone_key";
        } else if (Facebook.Name.equals(platformName)) {
            mIcon = "jiguang_socialize_facebook";
            mGrayIcon = "jiguang_socialize_facebook";
            mShowWord = "jiguang_socialize_text_facebook_key";
        } else if (FbMessenger.Name.equals(platformName)) {
            mIcon = "jiguang_socialize_messenger";
            mGrayIcon = "jiguang_socialize_messenger";
            mShowWord = "jiguang_socialize_text_messenger_key";
        }else if (Twitter.Name.equals(platformName)) {
            mIcon = "jiguang_socialize_twitter";
            mGrayIcon = "jiguang_socialize_twitter";
            mShowWord = "jiguang_socialize_text_twitter_key";
        }
        return ShareBoard.createSnsPlatform(mShowWord, mKeyword, mIcon, mGrayIcon, 0);
    }

    private void requestPermission() {
        ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_PHONE_STATE},
                REQUEST_PERMISSION);
    }

    public static String formatDate1(String dateStr) {
        DateFormat formatFrom = new SimpleDateFormat("MMM dd,yyyy", Locale.ENGLISH);
        Date date = null;
        try {
            date = formatFrom.parse(dateStr);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        DateFormat formatTo = new SimpleDateFormat("yyyy.MM.dd");
        return formatTo.format(date)+"";
    }
}
